// pages/showpage/showpage.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    showModal: false,
    clcikval: '',
    clcikid: '',
    youkey: '',
    page: 1,
    counts: 0,
    searchword: '',
    startX: 0, //开始坐标
    startY: 0,
  },

  //取查询输入值
  searchky: function (e) {
    this.setData({
      searchword: e.detail.value
    })

  },
  //查询
  searctxt: function () {

    if (this.data.searchword.replace(/(^\s*)|(\s*$)/g, "") == '') {
      wx.showToast({
        title: '查询内容不能为空！',
        icon: 'none',
      })
      return;
    }
    if (!app.globalData.userInfo) {
      wx.showToast({
        title: '先授权！',
        icon: 'none',
        duration: 1000
      })
      return;
    }
    //转到结果页
    wx.navigateTo({
      url: '../search/search?word=' + this.data.searchword,
    })
    this.setData({
      searchword: '',
    })
  },

  handleTouchStart: function (e) {
    this.startTime = e.timeStamp;
    //console.log(" startTime = " + e.timeStamp);  
    this.data.list.forEach(function (v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;

    })

    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      list: this.data.list

    })
  },
  //左滑
  handleTouchMove: function (e) {
    var that = this,
      index = e.target.dataset.dindex,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    that.data.list.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }


    })

    //更新数据
    that.setData({
      list: that.data.list,
      clcikid: e.currentTarget.dataset.rid
    })
  },

  /**
  * 计算滑动角度
  */

  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);

  },


  handleTouchEnd: function (e) {
    this.endTime = e.timeStamp;
  //   //console.log(" endTime = " + e.timeStamp);  
  },
  //点击弹出key框
  handleClick: function (e) {     //console.log("endTime - startTime = " + (this.endTime - this.startTime));    
    if (this.endTime - this.startTime < 350) {

      // if (!app.globalData.userInfo) {
      //   wx.showToast({
      //     title: '先授权！',
      //     icon: 'none',
      //     duration: 1000
      //   })
      //   return;
      // }
      //console.log("点击");
      //console.log(e.currentTarget.dataset.txt)
      this.setData({
        showModal: true,
        youkey:'',
        clcikval: e.currentTarget.dataset.txt,
      })
    }
  },
//删除
delOne:function(e){

  let that = this
  wx.showModal({
    title: '提示',
    content: '确认要删除此条信息么？',
    success: function (res) {
      if (res.confirm) {
        //console.log('用户点击确定')
        wx.showLoading({
          title: '删除中...',
        })
        that.data.list.splice(e.currentTarget.dataset.dindex, 1)
        that.setData({
          list: that.data.list,
        })
        //删数据库
        const db = wx.cloud.database()
        db.collection('person_memo').doc(that.data.clcikid).remove({
          success: function () {
            wx.hideLoading()
            wx.showToast({
              title: '删除成功！',
              icon: 'success',
            })
          },
          fail: function () {
            wx.showToast({
              title: '删除失败！',
              icon: 'none',
            })
          },
        })

      } else if (res.cancel) {
        // console.log('用户点击取消')
      }
    }
  })

},

  //长按 删除
  /*
  handleLongPress: function (e) {
    //console.log("endTime - startTime = " + (this.endTime - this.startTime));

    let that = this
    wx.showModal({
      title: '提示',
      content: '确认要删除此条信息么？',
      success: function (res) {
        if (res.confirm) {
          //console.log('用户点击确定')
          wx.showLoading({
            title: '删除中...',
          })
          that.data.list.splice(e.currentTarget.dataset.dindex, 1)
          that.setData({
            list: that.data.list,
            clcikid: e.currentTarget.dataset.rid
          })
          //删数据库
          const db = wx.cloud.database()
          db.collection('person_memo').doc(that.data.clcikid).remove({
            success: function () {
              wx.hideLoading()
              wx.showToast({
                title: '删除成功！',
                icon: 'success',
              })
            },
            fail: function () {
              wx.showToast({
                title: '删除失败！',
                icon: 'none',
              })
            },
          })

        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })
  },
  */
  //取输入的key值
  putkey: function (e) {
    this.setData({
      youkey: e.detail.value
    })
  },
  //弹出框点确定转到
  gotext: function () {

    if (this.data.youkey.replace(/(^\s*)|(\s*$)/g, "") == '') {
      wx.showToast({
        title: 'key不能为空！',
        icon: 'none',
      })
      return;
    }
    this.setData({
      showModal: false,
    })
    //console.log(this.data.clcikval)
    wx.navigateTo({
      url: '../mywords/mywords?k=' + this.data.youkey + '&descript=' + this.data.clcikval,
    })
  },
  //弹框取消
  canceltext: function () {
    this.setData({
      showModal: false
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  // onLoad: function (options) {
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  // onReady: function () {

  // },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.data.page = 1
    this.data.list = []
    this.setData({
      searchword: '',
    })
    let that = this

    if (!app.globalData.userInfo) {
      wx.showToast({
        title: '先授权！',
        icon: 'none',
      })
      return;
    }

    wx.showLoading({
      title: '加载中...',
    })
    // 显示列表

    const db = wx.cloud.database()

    //取记录数
    db.collection('person_memo').where({
      _openid: app.globalData.openid // 填入当前用户 openid
    }).count({
      success: function (res) {
        //console.log(res.total)
        that.data.counts = res.total
      }
    })
    //默认显示10条记录
    db.collection('person_memo').where({
      _openid: app.globalData.openid // 填入当前用户 openid
    }).limit(10)
      .get({
        success: function (res) {
          //console.log(res.data)

          wx.hideLoading()
          res.data.forEach(function (val, index) {
            that.data.list.push({
              rid: val._id,
              explain: val.description,
              etext: that.cutstr(val.encodetext),
              date: val.due,
              isTouchMove: false,
            })
          })

          that.setData({
            list: that.data.list.reverse(),

          })
        },
        fail: function () {
          wx.hideLoading()
          wx.showToast({
            title: '显示数据失败！请切换页面重试',
            icon: 'none',
          })
        },
      })

  },

  cutstr: function (s) {
    if (s.length > 26) {
      return s.slice(0, 26);
    } else {
      return s;
    }
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  // onHide: function () {

  // },

  /**
   * 生命周期函数--监听页面卸载
   */
  // onUnload: function () {

  // },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { //下拉加载更多
    if (!app.globalData.userInfo) {
      wx.showToast({
        title: '先授权！',
        icon: 'none',
      })
      wx.stopPullDownRefresh() //停止下拉刷新
      return;
    }

    wx.showNavigationBarLoading()
    

    let that = this
    const db = wx.cloud.database()
    if (this.data.page < Math.ceil(this.data.counts / 10)) {
      this.data.list = this.data.list.reverse()
      db.collection('person_memo').where({
        _openid: app.globalData.openid // 填入当前用户 openid
      }).skip(10 * that.data.page)
        .limit(10)
        .get({
          success: function (res) {
            //console.log(res.data)
            wx.hideNavigationBarLoading() //完成停止加载
            wx.stopPullDownRefresh() //停止下拉刷新

            res.data.forEach(function (val, index) {
              that.data.list.push({
                rid: val._id,
                explain: val.description,
                etext: that.cutstr(val.encodetext),
                date: val.due,
                isTouchMove: false,
              })
            })


            that.setData({
              list: that.data.list.reverse(),

            })
          }
        })

      console.log(Math.ceil(this.data.counts / 7))
    } else {
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
      wx.showToast({
        title: '已没有更多！',
        icon: 'none',
      })
      //console.log('没有内容了' + this.data.page)
    }
    this.data.page = this.data.page + 1

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  // onReachBottom: function () {

  // },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})